package com.wetool.controller.invoicing;

import java.security.Principal;
import java.util.List;
import javax.validation.Valid;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PagedResourcesAssembler;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.wetool.entity.invoicing.InvoicingCommodity;
import com.wetool.entity.invoicing.Supplier;
import com.wetool.exception.ParamCheckException;
import com.wetool.exception.invoicing.ShopNotLoginException;
import com.wetool.exception.invoicing.SpplitNotFindException;
import com.wetool.model.Message;
import com.wetool.model.Message.Result;
import com.wetool.model.invoicing.SearchParam;
import com.wetool.model.invoicing.SupplierAdd;
import com.wetool.model.invoicing.SupplierModify;
import com.wetool.service.invoicing.SupplierService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;

/**
 * 描述：供应商控制器
 * @author lixin
 */
@RestController
@RefreshScope
@RequestMapping("/suppliers")
@Api(description = "供应商管理")
public class SupplierController {
	private static final Logger logger = LogManager.getLogger(SupplierController.class);

	@Autowired
	private SupplierService supplierService;

	@ApiOperation(value="供应商列表", notes="查询已登录店铺的供应商列表", response = Message.class)
	@ApiImplicitParam(name = "id", value = "入库单Id", required = false, dataType = "Long", paramType = "path", defaultValue = "5")
    @ApiImplicitParams({
    	@ApiImplicitParam(name = "key", value = "供应商名称key", required = false, dataType = "String", paramType = "query", defaultValue = "t"),
    	@ApiImplicitParam(name = "page", value = "第几页", required = false, dataType = "int", paramType = "query", defaultValue = "0"),
    	@ApiImplicitParam(name = "size", value = "每页行数", required = false, dataType = "int", paramType = "query", defaultValue = "20"),
    	@ApiImplicitParam(name = "sort", value = "排序规则", required = false, dataType = "String", paramType = "query", defaultValue = "createDate,asc")
    })
	@ApiResponses(value = {
			@ApiResponse(code = 0, message = "操作成功！"),
			@ApiResponse(code = 1, message = "操作失败！"),
			@ApiResponse(code = 14,message = "店家未登录!")
	})
	@RequestMapping(value = "/list", method = RequestMethod.GET)
	public ResponseEntity<?> readSupplier(Principal principal, String key, Pageable p,Long shopId,
			PagedResourcesAssembler<Supplier> assembler) throws Exception {
		logger.info("进入接口>供应商列表 . 参数：店铺ID【{}】,查询参数【{}】",shopId,key);
		SearchParam searchParam = new SearchParam();
		searchParam.setShopId(shopId);
		searchParam.setKey(key);
		Page<Supplier> page = supplierService.findAll(searchParam, p);
		logger.info("结束接口>供应商列表 . 参数：供应商列表【{}】",page);
		return new ResponseEntity<>(new Message(Result.SUCCESS, assembler.toResource(page)), HttpStatus.OK);
	}
	
	@ApiOperation(value="入库提供供应商列表", notes="查询已登录店铺的入库提供供应商列表", response = Message.class)
    @ApiImplicitParam(name = "shopId", value = "店铺id", required = false, dataType = "String", paramType = "query", defaultValue = "t")
	@ApiResponses(value = {
			@ApiResponse(code = 0, message = "操作成功！"),
			@ApiResponse(code = 1, message = "操作失败！"),
			@ApiResponse(code = 14,message = "店家未登录!")
	})
	@RequestMapping(value = "/find", method = RequestMethod.GET)
	public ResponseEntity<?> find(Long shopId) throws Exception {
		logger.info("进入接口>入库提供供应商列表 . 参数：店铺ID【{}】,查询参数【{}】",shopId);
		List<Supplier> page = supplierService.findByShopId(shopId);
		logger.info("结束接口>入库提供供应商列表 . 参数：供应商列表【{}】",page);
		return new ResponseEntity<>(new Message(Result.SUCCESS, page), HttpStatus.OK);
	}
	
	@ApiOperation(value="查询供应商商品列表(停用)", notes="查询已登录店铺的供应商商品列表", response = Message.class)
    @ApiImplicitParams({
    	@ApiImplicitParam(name = "id", value = "供应商id", required = false, dataType = "Long", paramType = "path", defaultValue = "1"),
    	@ApiImplicitParam(name = "key", value = "商品名称或条码", required = false, dataType = "String", paramType = "query"),
    	@ApiImplicitParam(name = "page", value = "第几页", required = false, dataType = "int", paramType = "query", defaultValue = "0"),
    	@ApiImplicitParam(name = "size", value = "每页行数", required = false, dataType = "int", paramType = "query", defaultValue = "20"),
    	@ApiImplicitParam(name = "sort", value = "排序规则", required = false, dataType = "String", paramType = "query", defaultValue = "createDate,asc")
    })
	@ApiResponses(value = {
			@ApiResponse(code = 0, message = "操作成功！"),
			@ApiResponse(code = 1, message = "操作失败！"),
			@ApiResponse(code = 5, message = "未找到商品信息！"),
			@ApiResponse(code = 7, message = "未找到入库记录!"),
			@ApiResponse(code = 14,message = "店家未登录!")
	})
	@RequestMapping(value = "/findBySupplier/{id}", method = RequestMethod.GET)
	public ResponseEntity<?> findBySupplier(Principal principal,@PathVariable Long id,String key, Pageable p,
			PagedResourcesAssembler<Supplier> assembler) throws Exception {
		logger.info("进入接口>查询供应商商品列表(停用) . 参数：供应商ID【{}】,查询参数【{}】",id,key);
		SearchParam searchParam = new SearchParam();
		searchParam.setKey(key);
		searchParam.setStatus(1);
		searchParam.setSupplierId(id);
		 List<InvoicingCommodity> page = supplierService.findBySupplierToCommodity(searchParam,p);
		 logger.info("结束接口>查询供应商商品列表(停用) . 参数：商品列表集合【{}】",page);
		return new ResponseEntity<>(new Message(Result.SUCCESS, page), HttpStatus.OK);
	}
	
	@ApiOperation(value="查询对应编号的供应商", notes="查询已登录店铺的单个对应ID的供应商", response = Message.class)
    @ApiImplicitParam(name = "id", value = "供应商Id", required = true, dataType = "Long", paramType = "path", defaultValue = "1")
	@ApiResponses(value = {
			@ApiResponse(code = 0, message = "操作成功！"),
			@ApiResponse(code = 1, message = "操作失败！")
	})
	@RequestMapping(value = "/{id}", method = RequestMethod.GET)
	public ResponseEntity<?> getById(Principal principal,@PathVariable Long id, Pageable p,
			PagedResourcesAssembler<Supplier> assembler) {
		logger.info("进入接口>查询对应编号的供应商 . 参数：供应商ID【{}】",id);
		SupplierModify supplierModify = supplierService.findOne(id);
		logger.info("结束接口>查询对应编号的供应商");
		return new ResponseEntity<>(new Message(Result.SUCCESS, supplierModify), HttpStatus.OK);
	}
	
	@ApiOperation(value="修改对应编号的供应商", notes="查询已登录店铺的单个对应ID的供应商", response = Message.class)
    @ApiImplicitParam(name = "id", value = "供应商Id", required = true, dataType = "Long", paramType = "path", defaultValue = "1")
	@ApiResponses(value = {
			@ApiResponse(code = 0, message = "操作成功！"),
			@ApiResponse(code = 1, message = "操作失败！"),
			@ApiResponse(code = 14,message = "店家未登录!")
	})
	@RequestMapping(value = "/{id}", method = RequestMethod.PATCH)
	public ResponseEntity<?> update(Principal principal,@PathVariable Long id,
			@RequestBody SupplierModify supplierModify) throws ShopNotLoginException {
		logger.info("进入接口>修改对应编号的供应商 . 参数：供应商ID【{}】，供应商修改对象【{}】",id,supplierModify);
		supplierModify.setId(id);
		supplierService.updateSupplier(supplierModify);
		logger.info("结束接口>修改对应编号的供应商");
		return new ResponseEntity<>(new Message(Result.SUCCESS), HttpStatus.OK);
	}
	
	@ApiOperation(value="添加供应商信息", notes="已登录店铺的添加供应商", response = Message.class)
	@ApiResponses(value = {
			@ApiResponse(code = 0, message = "操作成功！"),
			@ApiResponse(code = 1, message = "操作失败！"),
			@ApiResponse(code = 10,message = "添加供应商失败！"),
			@ApiResponse(code = 14,message = "店家未登录!")
	})
	@RequestMapping(method = RequestMethod.POST)
	public ResponseEntity<?> creatSupplier( @Valid @RequestBody SupplierAdd supplierAdd,
			BindingResult bindingResult) throws Exception {
		logger.info("进入接口>添加供应商信息 . 参数：供应商添加对象【{}】",supplierAdd);
		if (bindingResult != null && bindingResult.getErrorCount() != 0) {
			throw new ParamCheckException(bindingResult);
		}
		Supplier su = supplierService.save(supplierAdd);
		logger.info("结束接口>添加供应商信息");
		return new ResponseEntity<>(new Message(Result.SUCCESS,su), HttpStatus.OK);
	}

	@ApiOperation(value="删除对应编号的供应商", notes="已登录店铺的删除单个对应ID的供应商", response = Message.class)
    @ApiImplicitParam(name = "id", value = "供应商Id", required = true, dataType = "Long", paramType = "path", defaultValue = "1")
	@ApiResponses(value = {
			@ApiResponse(code = 0, message = "操作成功！"),
			@ApiResponse(code = 1, message = "操作失败！"),
			@ApiResponse(code = 18, message = "未找到供应商信息!"),
			@ApiResponse(code = 14,message = "店家未登录!")
	})
	@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
	public ResponseEntity<?> delete(Principal principal,@PathVariable Long id,Long shopId) 
			throws SpplitNotFindException, ShopNotLoginException {
		logger.info("进入接口>删除对应编号的供应商 . 参数：供应商编号【{}】，供应商编号【{}】",shopId,id);
		if (shopId == null) {
			throw new ShopNotLoginException();
		}
		supplierService.delete(id);
		logger.info("结束接口>删除对应编号的供应商 ");
		return new ResponseEntity<>(new Message(Result.SUCCESS), HttpStatus.OK);
	}
}
